package com.zf.yichat.controller.message;

import com.github.pagehelper.PageHelper;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.dto.ChatroomAdminUserDto;
import com.zf.yichat.dto.ChatroomMemberUserDto;
import com.zf.yichat.dto.RcMessageSynchronizationDto;
import com.zf.yichat.dto.UserJoinChatroomDto;
import com.zf.yichat.dto.response.MessageDto;
import com.zf.yichat.im.mapper.RcMessageSynchronizationMapper;
import com.zf.yichat.mapper.UserJoinChatroomApplyMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.MessageChatroom;
import com.zf.yichat.model.RcMessageSynchronization;
import com.zf.yichat.model.User;
import com.zf.yichat.service.SecurityService;
import com.zf.yichat.service.config.ChatroomService;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.common.FsConst;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 11:08 2019/7/9 2019
 */
@Controller
@RequestMapping("message")
@Slf4j
public class MessageController extends BaseController {


    @Resource
    private RcMessageSynchronizationMapper rcMessageSynchronizationMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private ChatroomService chatroomService;

    @Resource
    private UserJoinChatroomApplyMapper userJoinChatroomApplyMapper;


    @RequestMapping("/index")
    public String index() {
        return "message/index";
    }

    @RequestMapping("/group/index")
    public String groupIndex() {
        return "message/group/index";
    }


    /**********************聊天室开始***************************************/
    /**
     * 聊天室列表
     * @return
     */
    @RequestMapping("/chatroom/index")
    public String chatroomIndex() {
        return "message/chatroom/index";
    }


    /**
     * 聊天室申请列表
     * @return
     */
    @RequestMapping("/chatroom/apply")
    public String chatroomApply() {
        return "message/chatroom/apply";
    }

    /**
     * 聊天室申请列表-审核操作
     * @return
     */
    @RequestMapping("/chatroom/applying")
    public String chatroomApplying(String userId, String chatroomId) {
        getRequest().setAttribute("userId", userId);
        getRequest().setAttribute("chatroomId", chatroomId);
        return "message/chatroom/applying";
    }

    /**
     * 聊天室管理员列表
     * @return
     */
    @RequestMapping("/chatroom/chatroomAdmin")
    public String chatroomAdmin(String chatroomId) {
        getRequest().setAttribute("chatroomId", chatroomId);
        return "message/chatroom/chatroomAdmin";
    }

    /**
     * 聊天室成员列表
     * @return
     */
    @RequestMapping("/chatroom/chatroomMember")
    public String chatroomMember(String chatroomId) {
        getRequest().setAttribute("chatroomId", chatroomId);
        return "message/chatroom/chatroomMember";
    }


    /**
     * 创建聊天室管理员
     * @param chatroomId
     * @param userIds
     * @return
     */
    @RequestMapping("/chatroom/createChatroomAdmin")
    @ResponseBody
    public FsResponse createChatroomAdmin(String chatroomId, String userIds) {
        try {
            if (StringUtils.isNotBlank(chatroomId) && StringUtils.isNotBlank(userIds)) {
                Integer code = chatroomService.createChatroomAdmin(chatroomId, userIds);
                if (FsConst.Status.IS_OK == code) {
                    return FsResponseGen.gen(true);
                }
            }
        } catch (Exception e) {
            log.info("创建聊天室管理员失败：", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 查询聊天室管理员
     * @param chatroomId
     * @return
     */
    @RequestMapping("/chatroom/chatroomAdminList")
    @ResponseBody
    public FsResponse queryChatroomAdmin(Integer page, Integer limit,String chatroomId, String userId, String nick, String mobile, String realName) {

        if (StringUtils.isBlank(chatroomId)) {
            return FsResponseGen.failMsg("参数错误[chatroomId]");
        }

        PageHelper.startPage(page, limit);
        List<ChatroomAdminUserDto> list = chatroomService.queryChatroomAdmin(chatroomId, userId, nick, mobile, realName);
        return DtoChangeUtils.getPageList(list, data -> {
            ChatroomAdminUserDto adminUserDto = new ChatroomAdminUserDto();
            BeanUtils.copyProperties(data, adminUserDto);
            return adminUserDto;
        });
    }

    /**
     * 查询聊天室成员列表
     * @param chatroomId
     * @return
     */
    @RequestMapping("/chatroom/chatroomMemberList")
    @ResponseBody
    public FsResponse queryChatroomMember(Integer page, Integer limit,String chatroomId, String userId, String nick, String mobile, String realName) {

        if (StringUtils.isBlank(chatroomId)) {
            return FsResponseGen.failMsg("参数错误[chatroomId]");
        }

        PageHelper.startPage(page, limit);
        List<ChatroomMemberUserDto> list = chatroomService.queryChatroomMember(chatroomId, userId, nick, mobile, realName);
        return DtoChangeUtils.getPageList(list, data -> {
            ChatroomMemberUserDto adminUserDto = new ChatroomMemberUserDto();
            BeanUtils.copyProperties(data, adminUserDto);
            return adminUserDto;
        });
    }

    /**
     * 删除聊天室管理员
     * @param chatroomId
     * @return
     */
    @RequestMapping("/chatroom/deleteChatroomAdmin")
    @ResponseBody
    public FsResponse deleteChatroomAdmin(String chatroomId,String userId) throws Exception {

        if (StringUtils.isBlank(chatroomId)) {
            return FsResponseGen.failMsg("参数错误[chatroomId]");
        }
        if (StringUtils.isBlank(userId)) {
            return FsResponseGen.failMsg("参数错误[userId]");
        }

        return FsResponseGen.successData(chatroomService.deleteChatroomAdmin(chatroomId, userId));
    }

    /**
     * 删除聊天室成员
     * @param chatroomId
     * @return
     */
    @RequestMapping("/chatroom/deleteChatroomMember")
    @ResponseBody
    public FsResponse deleteChatroomMember(String chatroomId,String userId) throws Exception {

        if (StringUtils.isBlank(chatroomId)) {
            return FsResponseGen.failMsg("参数错误[chatroomId]");
        }
        if (StringUtils.isBlank(userId)) {
            return FsResponseGen.failMsg("参数错误[userId]");
        }

        return FsResponseGen.successData(chatroomService.deleteChatroomMember(chatroomId, userId));
    }

    /**
     * 创建聊天室
     * @param name
     * @return
     */
    @RequestMapping("/chatroom/create")
    @ResponseBody
    public FsResponse chatroomCreate(String name) {
        try {
            if (StringUtils.isNotBlank(name)) {
                Integer code = chatroomService.createChatroom(name);
                if (FsConst.Status.IS_OK == code) {
                    return FsResponseGen.gen(true);
                }
            }
        } catch (Exception e) {
            log.info("创建聊天室失败：", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 编辑
     * @param status
     * @param chatroomName
     * @return
     */
    @RequestMapping("/updateChatroom")
    @ResponseBody
    public FsResponse chatroomUpdate(Long chatroomId, String status, String chatroomName) {

        chatroomService.chatroomUpdate(chatroomId, status, chatroomName);

        return FsResponseGen.success();
    }

    /**
     * 获取存活的聊天室
     * @return
     */
    @RequestMapping("/chatroom/query")
    @ResponseBody
    public FsResponse chatroomQuery() {
        try {
            List<MessageChatroom> chatroomList = chatroomService.getChatroomList();
            return FsResponseGen.successData(chatroomList);
        } catch (Exception e) {
            log.info("获取存活的聊天室失败：", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 删除聊天室
     * @return
     */
    @RequestMapping("/chatroom/delete")
    @ResponseBody
    public FsResponse chatroomDelete(String chatroomId) {
        try {
            boolean isDel = chatroomService.chatroomDelete(chatroomId);
            return FsResponseGen.gen(isDel);
        } catch (Exception e) {
            log.info("创建聊天室失败：", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 审核申请入聊天室成员
     * @return
     */
    @RequestMapping("/chatroom/applyed")
    @ResponseBody
    public FsResponse chatroomApplyed(String chatroomId, String userId, String status) {
        try {
            chatroomService.chatroomApply(chatroomId, userId, status);
            return FsResponseGen.success();
        } catch (Exception e) {
            log.info("审核申请入聊天室成员失败：", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 单聊记录列表
     * @param page
     * @param limit
     * @param sendId
     * @param appId
     * @param content
     * @param sendName
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public FsResponse list(Integer page, Integer limit, Long sendId, String appId,
                           String content, String sendName,String userId,
                           String startTime, String endTime) {
        Long stime = null;
        Long etime = null;
        //将时间转化为数值
        if (StringUtils.isNotBlank(startTime)) {
            stime = DateUtils.parse(startTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss").getTime();
        }

        if (StringUtils.isNotBlank(endTime)) {
            etime = DateUtils.parse(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss").getTime();
        }

        // 如果没有传page参数，默认取全部数据
        if (null == page) {
            page = 1;
        }
        if (null == limit) {
            limit = Integer.MAX_VALUE;
        }


        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(rcMessageSynchronizationMapper.selectSingleChatList(sendId, "PERSON", sendName, stime, etime, content), copy -> {
            MessageDto dto = new MessageDto();
            dto.setSendName(copy.getSendName());
            dto.setReceiveName(copy.getReceiverName());
            dto.setId(copy.getId());
            dto.setFromUserId(copy.getFromUserId());
            dto.setText(copy.getText());
            dto.setToUserId(copy.getToUserId());
            dto.setChannelType(copy.getChannelType());
            long timestamp = copy.getMsgTimestamp();
            dto.setCreateTime(DateUtils.timestampConversion(timestamp, DateUtils.yyyyMMddHHmmss18));
            dto.setObjectName(copy.getObjectName());
            dto.setContent(copy.getContent());

            return dto;
        });
    }

    /**
     * 群聊记录列表
     * @param page
     * @param limit
     * @param sendId
     * @param appId
     * @param sendName
     * @param startTime
     * @param endTime
     * @param content
     * @return
     */
    @RequestMapping("/group/list")
    @ResponseBody
    public FsResponse groupList(Integer page, Integer limit, Long sendId, String appId, String sendName, String startTime, String endTime, String content) {

        //将时间转化为数值
        Long stime = null;
        Long etime = null;
        if (StringUtils.isNotBlank(startTime)) {
            stime = DateUtils.parse(startTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss").getTime();
        }

        if (StringUtils.isNotBlank(endTime)) {
            etime = DateUtils.parse(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss").getTime();
        }

        if (null == page) {
            page = 1;
        }
        if (null == limit) {
            limit = Integer.MAX_VALUE;
        }

        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(rcMessageSynchronizationMapper.selectGroupChatList(sendId, "GROUP", sendName, stime, etime, content), copy -> {
            MessageDto dto = new MessageDto();
            dto.setSendName(copy.getSendName());
            dto.setReceiveName(copy.getGroupName());
            dto.setId(copy.getId());
            dto.setFromUserId(copy.getFromUserId());
            dto.setText(copy.getText());
            dto.setToUserId(copy.getToUserId());
            dto.setChannelType(copy.getChannelType());
            long timestamp = copy.getMsgTimestamp();
            dto.setCreateTime(DateUtils.timestampConversion(timestamp, DateUtils.yyyyMMddHHmmss18));
            dto.setObjectName(copy.getObjectName());
            dto.setContent(copy.getContent());

            return dto;
        });
    }



    /**
     * 用户列表-单聊记录
     * @param fromUserId
     * @param toUserId
     * @return
     */
    @RequestMapping("/person/singleChatRecord")
    @ResponseBody
    public FsResponse singleChatRecord(Long fromUserId, Long toUserId) {

        List<RcMessageSynchronizationDto> singleChatRecord = rcMessageSynchronizationMapper.singleChatRecord(fromUserId, toUserId);
        return DtoChangeUtils.getPageList(singleChatRecord, record -> {
            RcMessageSynchronizationDto dto = new RcMessageSynchronizationDto();
            dto.setFromUserId(record.getFromUserId());
            dto.setToUserId(record.getToUserId());

            dto.setCreateTime(DateUtils.timestampConversion(record.getMsgTimestamp(), DateUtils.yyyyMMddHHmmss18));
            dto.setSendName(record.getSendName());
            dto.setReceiverName(record.getReceiverName());
            dto.setText(record.getText());
            dto.setSendPortraitUri(record.getSendPortraitUri());
            dto.setReceiverPortraitUri(record.getReceiverPortraitUri());
            dto.setObjectName(record.getObjectName());
            dto.setContent(record.getContent());
            return dto;
        });
    };

    /**
     * 用户列表-群聊记录
     * @param groupId
     * @return
     */
    @RequestMapping("/person/groupChatRecord")
    @ResponseBody
    public FsResponse groupChatRecord(Long groupId) {

        List<RcMessageSynchronizationDto> singleChatRecord = rcMessageSynchronizationMapper.groupChatRecord(groupId);
        return DtoChangeUtils.getPageList(singleChatRecord, record -> {
            RcMessageSynchronizationDto dto = new RcMessageSynchronizationDto();
            BeanUtils.copyProperties(record, dto);
            dto.setCreateTime(DateUtils.timestampConversion(record.getMsgTimestamp(), DateUtils.yyyyMMddHHmmss18));
            return dto;
        });
    };

    /**
     * 用户申请进聊天室列表
     * @return
     */
    @RequestMapping("/chatroom/userApplyList")
    @ResponseBody
    public FsResponse userApplyList(Integer page, Integer limit) {

        PageHelper.startPage(page, limit);
        List<UserJoinChatroomDto> list = userJoinChatroomApplyMapper.selectList();
        return DtoChangeUtils.getPageList(list, record -> {

            UserJoinChatroomDto chatroomDto = new UserJoinChatroomDto();
            BeanUtils.copyProperties(record, chatroomDto);
            return chatroomDto;
        });
    }

    @RequestMapping("/status/update")
    @ResponseBody
    public FsResponse statusUpdate(Long id, Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        userMapper.updateByPrimaryKeySelective(user);
        return FsResponseGen.success();
    }

    @RequestMapping("/clean/login/status")
    @ResponseBody
    public FsResponse cleanToken(Long id) {
        securityService.clearToken(id);
        return FsResponseGen.success();
    }


    @RequestMapping("/clean")
    @ResponseBody
    public FsResponse cleanMsg(Long limitDate) {
        rcMessageSynchronizationMapper.cleanMsg(limitDate);
        return FsResponseGen.success();
    }


    @RequestMapping("/clean/single")
    @ResponseBody
    public FsResponse cleanSingle(Integer id) {
        rcMessageSynchronizationMapper.deleteById(id);
        return FsResponseGen.success();
    }

}
